package com.corpgovernment.organization.service.impl;

import com.corpgovernment.api.operatelog.chooseconstant.ChooseOperationType;
import com.corpgovernment.api.operatelog.vo.OperateLogContentDataVo;
import com.corpgovernment.api.organization.model.idcard.MbOrgUserIdcardDto;
import com.corpgovernment.api.organization.model.idcard.UserIdCardVo;
import com.corpgovernment.common.base.CommonException;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.dto.UserCardValidationInfoReqVo;
import com.corpgovernment.common.utils.CardValidateUtil;
import com.corpgovernment.common.utils.DateUtil;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.convert.PassengerConvert;
import com.corpgovernment.organization.convert.UserCardInfoConvert;
import com.corpgovernment.organization.entity.db.MbOrgUserIdcard;
import com.corpgovernment.organization.mapper.MbOrgUserIdcardMapper;
import com.corpgovernment.organization.service.IOrgUserIdCardService;
import com.corpgovernment.organization.service.OrganizationBaseService;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户证件信息serviceImpl
 *
 * @author wangyujue
 */
@Service
@Slf4j
public class OrgUserIdCardServiceImpl extends OrganizationBaseService implements IOrgUserIdCardService {

    @Autowired
    private MbOrgUserIdcardMapper orgUserIdcardMapper;
    @Autowired
    private UserCardInfoConvert userCardInfoConvert;

    @Override
    public boolean create(MbOrgUserIdcard mbOrgUserIdcard) {
        int i = orgUserIdcardMapper.insertSelective(mbOrgUserIdcard);
//        insertOperateLog(mbOrgUserIdcard);
        return i > 0;
    }

    @Override
    public boolean updateEmployeeCard(MbOrgUserIdcard mbOrgUserIdcard) {
        int i = orgUserIdcardMapper.updateByEmployeeUid(mbOrgUserIdcard);
        try {
            MbOrgUserIdcard oldValue = orgUserIdcardMapper.selectByPrimaryKey(mbOrgUserIdcard.getEmployeeUid());
            updateOperateLog(oldValue, mbOrgUserIdcard);
        } catch (Exception e) {
            log.error("更新操作获取oldValue失败，OrganizationUserIdCardServiceImpl.updateEmployeeCard");
        }
        return i > 0;
    }

    @Override
    public boolean update(MbOrgUserIdcard mbOrgUserIdcard) {
        int i = orgUserIdcardMapper.updateByPrimaryKeySelective(mbOrgUserIdcard);
        return i > 0;
    }

    @Override
    public List<MbOrgUserIdcard> findByEmployeeUid(String employeeUid) {
        MbOrgUserIdcard selectParam = new MbOrgUserIdcard();
        selectParam.setEmployeeUid(employeeUid);
        selectParam.setDeleteTime(new Date(0));
        List<MbOrgUserIdcard> result = orgUserIdcardMapper.select(selectParam);
        return result;
    }

    @Override
    public boolean delete(Integer id) {
        MbOrgUserIdcard mbOrgUserIdcard = new MbOrgUserIdcard();
        mbOrgUserIdcard.setId(Long.valueOf(id));
        int delete = orgUserIdcardMapper.delete(mbOrgUserIdcard);
        deleteOperateLog(String.valueOf(id));
        return delete > 0;
    }

    @Override
    public boolean deleteByEmployeeUid(String uid) {
        int i = orgUserIdcardMapper.deleteByEmployeeUid(uid);
        deleteOperateLog(uid);
        return i > 0;
    }

    @Override
    public boolean deleteByNonEmployeeUid(Long nonEmployeeUid) {
        return orgUserIdcardMapper.deleteByNonEmployeeUid(nonEmployeeUid) > 0;
    }

    @Override
    public MbOrgUserIdcard findByEmployeeUidAndType(String uid, Integer cardType) {

        if (StringUtils.isEmpty(uid) || cardType == null) {
            return null;
        }

        MbOrgUserIdcard selectParam = new MbOrgUserIdcard();
        selectParam.setEmployeeUid(uid);
        selectParam.setCardType(cardType);
//        selectParam.setDeleted(false);
        selectParam.setDeleteTime(new Date(0));
        return orgUserIdcardMapper.selectOne(selectParam);
    }

    @Override
    public MbOrgUserIdcard findByNonEmployeeUidAndType(Long nonEmployeeUid, Integer cardType) {

        if (nonEmployeeUid == null || nonEmployeeUid <= 0 || cardType == null) {
            return null;
        }

        MbOrgUserIdcard selectParam = new MbOrgUserIdcard();
        selectParam.setNonEmployeeId(nonEmployeeUid);
        selectParam.setCardType(cardType);
//        selectParam.setDeleted(false);
        selectParam.setDeleteTime(new Date(0));
        return orgUserIdcardMapper.selectOne(selectParam);
    }

    @Override
    public List<MbOrgUserIdcard> batchFindByUids(List<String> uids) {
        return orgUserIdcardMapper.listByUids(uids);
    }

    @Override
    public List<MbOrgUserIdcard> batchFindByNonEmployeeUids(List<Long> nonEmployeeUids) {
        return orgUserIdcardMapper.listByNonEmployeeUids(nonEmployeeUids);
    }

    @Override
    public boolean batchSave(List<MbOrgUserIdcard> needAddList) {

        if (CollectionUtils.isEmpty(needAddList)) {
            return false;
        }
        return orgUserIdcardMapper.batchSave(needAddList) > 0;
    }

    @Override
    public boolean updateNonEmployeeCard(MbOrgUserIdcard mbOrgUserIdcard) {
        try {
            MbOrgUserIdcard selectParam = new MbOrgUserIdcard();
            selectParam.setNonEmployeeId(mbOrgUserIdcard.getNonEmployeeId());
//            selectParam.setDeleted(false);
            selectParam.setDeleteTime(new Date(0));
            selectParam.setCardType(mbOrgUserIdcard.getCardType());
            MbOrgUserIdcard oldValue = orgUserIdcardMapper.selectOne(selectParam);

            List<OperateLogContentDataVo> operateLogContentDataVos = Lists.newArrayList(new OperateLogContentDataVo("有效截止日期", DateUtil.dateToString(oldValue.getTimeLimit()), DateUtil.dateToString(mbOrgUserIdcard.getTimeLimit()), ChooseOperationType.UPDATE));
            updateOperateLog(String.valueOf(oldValue.getId()), operateLogContentDataVos);
        } catch (Exception e) {
            log.error("更新操作获取查询失败，OrganizationUserIdCardServiceImpl.updateNonEmployeeCard");
        }
        int i = orgUserIdcardMapper.updateByNonEmployeeUid(mbOrgUserIdcard);
        return i > 0;
    }

    @Override
    public MbOrgUserIdcardDto selectCardInfo(Integer cardType, String cardNo) {

        List<MbOrgUserIdcard> result = listEmployeeByTypeAndNo(cardType, cardNo);
        if (CollectionUtils.isEmpty(result)) {
            throw new CommonException("card info not exist");
        }
        MbOrgUserIdcardDto mbOrgUserIdcardDto = new MbOrgUserIdcardDto();
        BeanUtils.copyProperties(result.get(0), mbOrgUserIdcardDto);
        return mbOrgUserIdcardDto;
    }

    @Override
    public List<MbOrgUserIdcard> listEmployeeByTypeAndNo(Integer type, String cardNo) {

        if (type == null) {
            return null;
        }

        MbOrgUserIdcard cardQuery = new MbOrgUserIdcard();
        cardQuery.setCardNo(cardNo);
        cardQuery.setCardType(type);
//        cardQuery.setDeleted(false);
        cardQuery.setDeleteTime(new Date(0));
        return orgUserIdcardMapper.select(cardQuery);
    }

    @Override
    public List<MbOrgUserIdcard> listByNo(String cardNo) {

        MbOrgUserIdcard cardQuery = new MbOrgUserIdcard();
        cardQuery.setCardNo(cardNo);
//        cardQuery.setDeleted(false);
        cardQuery.setDeleteTime(new Date(0));
        return orgUserIdcardMapper.select(cardQuery);
    }

    @Override
    public boolean save(MbOrgUserIdcard mbOrgUserIdcard) {
//        insertOperateLog(mbOrgUserIdcard);
        return orgUserIdcardMapper.insertSelective(mbOrgUserIdcard) > 0;
    }

    @Override
    public boolean saveList(List<MbOrgUserIdcard> mbOrgUserIdCardList) {

        if (CollectionUtils.isEmpty(mbOrgUserIdCardList)) {
            return false;
        }
        return orgUserIdcardMapper.insertList(mbOrgUserIdCardList) > 0;
    }

    @Override
    public List<MbOrgUserIdcard> findByTypeAndNo(Integer type, String cardNo) {

        if (type == null) {
            return new ArrayList<>();
        }
        return orgUserIdcardMapper.listEmployeeByTypeAndNo(type, cardNo);
    }

    @Override
    public boolean validateCardInfo(UserIdCardVo userIdCardVo) {
        UserCardValidationInfoReqVo userCardValidationInfoReqVo =
                userCardInfoConvert.convertToUserCardValidationInfo(userIdCardVo);
        return CardValidateUtil.validateUserCard(userCardValidationInfoReqVo);
    }

    @Override
    public List<MbOrgUserIdcard> findByTypeAndNo(Integer type, String cardNo, boolean nonEmployee) {
        if (Objects.isNull(type) || StringUtils.isBlank(cardNo)) {
            return Collections.emptyList();
        }
        List<MbOrgUserIdcard> orgUserIdcardList = findByTypeAndNo(type, cardNo);
        if (CollectionUtils.isNotEmpty(orgUserIdcardList)) {
            // 外部员工
            if (nonEmployee) {
                return orgUserIdcardList.stream()
                    .filter(item -> Objects.nonNull(item.getNonEmployeeId()) && item.getNonEmployeeId() > 0)
                    .collect(Collectors.toList());
            } else {
                // 内部员工
                return orgUserIdcardList.stream().filter(item -> StringUtils.isNotBlank(item.getEmployeeUid()))
                    .collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }

    @Override
	public List<MbOrgUserIdcard> getLikeCardNo(String cardNo) {
		if ( StringUtils.isBlank(cardNo)) {
			return new ArrayList<>();
		}
		MbOrgUserIdcard selectParam = new MbOrgUserIdcard();
		selectParam.setDeleteTime(new Date(0));
		List<MbOrgUserIdcard> list = orgUserIdcardMapper.select(selectParam);
		return list.stream().filter(e-> org.apache.commons.lang.StringUtils.contains(e.getCardNo(), cardNo)).collect(Collectors.toList());
	}

	@Override
	public List<MbOrgUserIdcard> getByUids(List<String> uids) {
		if (CollectionUtils.isEmpty(uids)) {
			return new ArrayList<>();
		}
		return orgUserIdcardMapper.listByUids(uids);
	}

    @Override
    public boolean deleteByUids(List<String> uids) {
        if (CollectionUtils.isEmpty(uids)){
            return false;
        }
        Example example = new Example(MbOrgUserIdcard.class);
        example.createCriteria().andIn("employeeUid", uids).andEqualTo("deleteTime", new Date(0));
        MbOrgUserIdcard mbOrgUserIdcard = new MbOrgUserIdcard();
        mbOrgUserIdcard.setDeleteTime(new Date());
        return orgUserIdcardMapper.updateByExampleSelective(mbOrgUserIdcard, example) >0;
    }

    @Override
    public boolean insertList(List<MbOrgUserIdcard> mbOrgUserIdcardList) {
        if (CollectionUtils.isEmpty(mbOrgUserIdcardList)){
            return false;
        }
        return orgUserIdcardMapper.insertList(mbOrgUserIdcardList) >0;
    }

    @Override
    public boolean deleteByList(List<MbOrgUserIdcard> mbOrgUserIdCardList) {
        if (CollectionUtils.isEmpty(mbOrgUserIdCardList)){
            return false;
        }
        mbOrgUserIdCardList.forEach(e ->{
            e.setDeleteTime(new Date());
        });
        return orgUserIdcardMapper.updateBatchSelective(mbOrgUserIdCardList) > 0;
    }

    @Override
    public List<MbOrgUserIdcard> findByNonEmployeeId(Long id) {
        if (Objects.isNull(id)){
            return new ArrayList<>();
        }
        MbOrgUserIdcard selectParam = new MbOrgUserIdcard();
        selectParam.setNonEmployeeId(id);
        selectParam.setDeleteTime(new Date(0));
        return orgUserIdcardMapper.select(selectParam);
    }
}
